//
//  YMJCoverFlow.m
//  QQ12星座
//
//  Created by dllo on 16/7/25.
//  Copyright © 2016年 YMJ. All rights reserved.
//

#import "YMJCoverFlow.h"

@implementation YMJCoverFlow
- (void) prepareLayout {
    [super prepareLayout];
}
- (BOOL)shouldInvalidateLayoutForBoundsChange:(CGRect)newBounds {
    return YES;
}
- (nullable NSArray<__kindof UICollectionViewLayoutAttributes *> *)layoutAttributesForElementsInRect:(CGRect)rect {
    CGFloat centerX = self.collectionView.contentOffset.x + self.collectionView.bounds.size.width / 2;
    NSArray *array = [super layoutAttributesForElementsInRect:rect];
    for (UICollectionViewLayoutAttributes *arr in array) {
        CGFloat cell_centerX = arr.center.x ;
        CGFloat distance_center = ABS(cell_centerX - centerX);
        CGFloat factor = 0.003;
        CGFloat scale = 1 / (1 + distance_center * factor);
        arr.transform = CGAffineTransformMakeScale(scale, scale);
        arr.size = CGSizeMake(self.itemSize.width * 1.5, self.itemSize.height * 1.5);

    }
    return array;
}
- (CGPoint)targetContentOffsetForProposedContentOffset:(CGPoint)proposedContentOffset withScrollingVelocity:(CGPoint)velocity {
//    CGFloat proposeX = proposedContentOffset.x + self.collectionView.frame.size.width;
//    CGFloat proposeY = proposedContentOffset.y + self.collectionView.frame.size.height;
    CGFloat proposeW = self.collectionView.frame.size.width;
    CGFloat proposeH = self.collectionView.frame.size.height;
    CGRect rect = CGRectMake(proposedContentOffset.x, proposedContentOffset.y, proposeW, proposeH);
    NSArray *array = [super layoutAttributesForElementsInRect:rect];
    int min_index = 0;
    UICollectionViewLayoutAttributes *min_attribute = array[min_index];
    CGFloat centerX = proposedContentOffset.x + self.collectionView.frame.size.width / 2;
    for (int i = 0; i < array.count; i++) {
        UICollectionViewLayoutAttributes *temp = array[i];
        CGFloat temp_x= temp.center.x;
        
        if (ABS(min_attribute.center.x - centerX) > ABS(temp_x - centerX)) {
            min_index = i;
            min_attribute = temp;
        }
    }
    CGFloat minDistance_cell_x  = min_attribute.center.x - centerX;
    return CGPointMake(proposedContentOffset.x + minDistance_cell_x, proposedContentOffset.y);
    
}
@end
